package com.renl.juc.prodconsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author renl
 * @date 2020/1/7
 * 传统的生产者消费者模型
 *
 * 虚假唤醒
 */
class shareData{
  private int number = 0;
  private Lock lock = new ReentrantLock();
  private Condition condition = lock.newCondition();
  public void increment(){
    try {
      lock.lock();
//      while (number != 0 ){
        if (number != 0 ){

          //wait,cant product
        try {
          condition.await();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      //working
      number++;
      System.out.println(Thread.currentThread().getName() + "\t product " + number);
      condition.signal();
    }finally {
      lock.unlock();
    }
  }
  public void decrement(){
    try {
      lock.lock();
        if (number == 0 ){
//        while (number == 0 ){
        //wait,cant product
        try {
          condition.await();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      //working
      number--;
      System.out.println(Thread.currentThread().getName() + "\t consume " + number);
      condition.signal();
    }finally {
      lock.unlock();
    }
  }
}

public class ProdConsumer_TranditionDemo {
  public static void main(String[] args) {
    shareData shareData = new shareData();
    new Thread(() -> {
//      for (int i = 0 ; i < 5 ; i++){
        shareData.increment();
//      }
    },"a").start();
    new Thread(() -> {
//      for (int i = 0 ; i < 5 ; i++){
        shareData.decrement();
//      }
    },"b").start();
  }
}
